(function () {
  new Vue({
    el: '#contractChangeIndex',
    data() {
      return {
        id: hlUrlUtil.GetQueryString('id'), //合同ID
        code: hlUrlUtil.GetQueryString('code'), //变更code
        alterId: hlUrlUtil.GetQueryString('alertId'), //变更ID
        mode: hlUrlUtil.GetQueryString('mode') || 'create', //变更模式
        mCode: '', //合同管理编号


        updateTime: '', //变更生效日
        instr: '', //变更说明
        tabList: [{
          name: '基本信息变更',
          code: 'YB',
        }, {
          name: '条款变更',
          code: 'CW',
        }, {
          name: '补充协议',
          code: 'AG',
        }],
        tabActive: [],
        contractDetail: '',

        fileList: [],
        progress: '',
      }
    },
    methods: {
      // 上传文件
      uploadFile: function () {
        if (this.progress) {
          hl.toast('文件尚未上传完成')
          return
        }
        $('.upload-file-button').trigger('click')
      },
      delFileItem(index) {
        this.fileList.splice(index, 1)
      },
      //获取变更详情
      getAlertDetail() {
        hlhttp.get({
          url: 'contract_history',
          data: {
            alter_id: this.alterId
          },
          success: (data) => {
            this.code = data.alterInfoVO.alterNo
            this.tabActive = data.alterInfoVO.alterType == 'ALL' ? ['YB', 'CW'] : data.alterInfoVO.alterType.split(',')
            if (data.alterInfoVO.agreementFlag == 'Y') {
              if (this.tabActive.indexOf('AG') == -1) {
                this.tabActive.push('AG')
              }
              let arrName = []
              let arrUrl = []
              arrName = data.alterInfoVO.agreementAttachmentNames.split(',')
              arrUrl = data.alterInfoVO.agreementAttachmentUrls.split(',')
              arrName.map((item, index) => {
                this.fileList.push({
                  name: item,
                  url: arrUrl[index]
                })
              })
            }
            this.instr = data.alterInfoVO.alertDescription
            this.updateTime = hlDateUtil.formatUTCDate(data.alterInfoVO.effectiveDate, 'yyyy-MM-dd')
            this.initContractDetail(data)
          }
        })
      },
      // 获取合同详情
      getDetail() {
        let that = this
        hlhttp.get({
          url: 'contract',
          data: {
            id: that.id
          },
          success(res) {
            that.initContractDetail(res)
          }
        })
      },
      // 初始化合同详情
      initContractDetail(res) {
        res.tmpData = res.pageCustomizeComponentBizContentList ? res.pageCustomizeComponentBizContentList : []
        res.resData = [];
        this.mCode = res.mCode
        res.sign_time = hlDateUtil.formatUTCDate(res.signTime || res.alterInfoVO.signTime, 'yyyy-MM-dd')
        res.begin_date = hlDateUtil.formatUTCDate(res.beginDate, 'yyyy-MM-dd')
        res.end_date = hlDateUtil.formatUTCDate(res.endDate, 'yyyy-MM-dd')
        res.zlfType = [res.zlfType]
        res.zlfIndustryType = [res.zlfIndustryType]
        res.id = res.id
        res.channelCategoryCode = [res.channelCategoryCode]
        res.channelNameCode = res.channelNameCode ? res.channelNameCode : ''
        res.ZDYdata = res.customConfigProperty ? JSON.parse(res.customConfigProperty) : []
        res.selectStationList = [] //选中工位列表（展示）在工位选择模块
        res.selectParkList = [] //确认选中车位 在车位选择模块
        res.selectUnitList = [] //确认选中单元 在单元选择模块

        res.intent = {
          id: null,
          intentDeductibleAmount: null
        }

        if (res.relatedIntentId) {
          res.intent = {
            id: res.relatedIntentId,
            intentDeductibleAmount: res.intentDeductibleAmount
          }
        }

        if (res.contractType == 'ER') {
          res.units.map(item => {
            item.building_id = item.buildingId
            item.building_name = item.buildingName
            item.floor_id = item.floorId
            item.floor_name = item.floorName
            item.floor_num = item.floorNum
            item.unit_name = item.unitName
            item.unit_id = item.unitId
            item.unit_acreage = item.unitAcreage
						item.business_type = item.businessType
            item.stops = []
            item.positions.map(single => {
              item.stops.push({
                stop_id: single.positionId,
                stop_name: single.positionName,
								business_type: single.businessType
              })
            })
            if (item.unitType == 'ST') {
              res.selectParkList.push(item)
            } else {
              res.selectUnitList.push(item)
            }
          })
        } else {
          res.units.map(item => {
            item.building_id = item.buildingId
            item.building_name = item.buildingName
            item.floor_id = item.floorId
            item.floor_name = item.floorName
            item.floor_num = item.floorNum
            item.unit_name = item.unitName
            item.unit_id = item.unitId
            item.unit_acreage = item.unitAcreage
						item.business_type = item.businessType
            item.stops = []
            item.positions.map(single => {
              item.stops.push({
                stop_id: single.positionId,
                stop_name: single.positionName,
								business_type: single.businessType
              })
            })
            if (item.unitType == 'ST') {
              res.selectParkList.push(item)
            } else {
              res.selectStationList.push(item)
            }
          })
        }
        this.contractDetail = res
      },
      // 下一步之前的校验
      nextCheck() {
        if (!this.updateTime) {
          hl.toast('请选择时间')
          return false
        }
        if (this.tabActive.indexOf('YB') == -1 && this.tabActive.indexOf('CW') == -1) {
          hl.toast('请选择变更内容')
          return false
        }
        if (this.tabActive.indexOf('AG') != -1) {
          if (!this.fileList.length) {
            hl.toast('请上传补充协议')
            return false
          }
        }
        return true
      },
      next() {
        if (!this.nextCheck()) return
        let data = {
          "alter_no": this.code,
          "alert_description": this.instr,
          "alter_type": this.tabActive + '',
          "effective_date": this.updateTime,
          "m_code": this.mCode,
          "alter_id": this.alterId || '#',
          "agreement_flag": this.tabActive.indexOf('AG') != -1 ? 'Y' : 'N',
          "agreement_attachment_urls": '#',
          "agreement_attachment_names": '#',
        }
        let name = []
        let url = []
        if (this.fileList.length) {
          this.fileList.map(item => {
            name.push(item.name)
            url.push(item.url)
          })
          data.agreement_attachment_urls = url + ''
          data.agreement_attachment_names = name + ''
        }

        window.sessionStorage.setItem('CHANGE_CONTRACT_INDEX', JSON.stringify(data))
        window.sessionStorage.setItem('CONTRACT_DETAIL', JSON.stringify(this.contractDetail))
        hlUrlUtil.goTo('contractChange', {
          'id': this.id,
          'code': this.code,
          condition: this.tabActive,
          mode: this.mode
        })
      },
      // 保存提交审批
      saveChangeContract(num) {
        //num == 0 为保存草稿（草稿有编辑，创建状态） 1位提交审批（创建直接提交。草稿提交审批）
        if (!this.updateTime) {
          hl.toast('请选择时间')
          return
        }
        if (!this.fileList.length) {
          hl.toast('请上传补充协议')
          return
        }
        let data = {
          alter_no: this.code,
          alter_type: this.tabActive + '',
          alert_description: this.instr || '#',
          effective_date: this.updateTime,
          contract_id: this.id,
          m_code: this.mCode,
          c_code: this.contractDetail.cCode || '#',
          contract_type: this.contractDetail.contractType,
          agreement_flag: 'Y',
          agreement_attachment_urls: '',
          agreement_attachment_names: '',
        }
        let name = []
        let url = []
        this.fileList.map(item => {
          name.push(item.name)
          url.push(item.url)
        })
        data.agreement_attachment_urls = url + ''
        data.agreement_attachment_names = name + ''
        if (!num) {
          if (this.mode == 'edit') {
            data.alter_id = this.alterId
            hlhttp.put({
              url: 'agreement/contract_history',
              data: data,
              success(res) {
                hl.toast('保存成功')
                this.clearStorage()
                hlUrlUtil.goTo('contractUpdateList')
              }
            })
          } else {
            hlhttp.post({
              url: 'agreement/contract_history',
              data: data,
              success(res) {
                hl.toast('保存成功')
                this.clearStorage()
                hlUrlUtil.goTo('contractUpdateList')
              }
            })
          }
        } else {
          if (this.mode == 'edit') {
            data.alter_id = this.alterId
            hlhttp.put({
              url: 'agreement/contract_history/_submit',
              data: data,
              success(res) {
                hl.toast('提交成功')
                this.clearStorage()
                hlUrlUtil.goTo('contractUpdateList')
              }
            })
          } else {
            data.alter_id = '#'
            hlhttp.put({
              url: 'agreement/contract_history/_submit',
              data: data,
              success(res) {
                hl.toast('提交成功')
                this.clearStorage()
                hlUrlUtil.goTo('contractUpdateList')
              }
            })
          }
        }
      },
      // 清缓存
      clearStorage() {
        var keyArr = [
          'CHANGE_CONTRACT_INDEX',
          'CHANGE_CONTRACT_GROUPLOPS',
          'CHANGE_CONTRACT_CONTRAST',
          'CHANGE_CONTRACT_002',
          'pageIndex',
          'CONTRACT_DETAIL'
        ]
        hlStorage.ssClearMultipleKey(keyArr)
      },
      // 选择时间
      selectDate() {
        let B = hlDateUtil.shellDate(this.contractDetail.begin_date)
        let N = hlDateUtil.shellDate(this.updateTime)
        let E = hlDateUtil.shellDate(this.contractDetail.end_date)
        if (N < B || N > E) {
          hl.toast('变更生效日需在合同租约期内')
          setTimeout(() => {
            this.updateTime = ''
          }, 100)
        }
      },
    },
    mounted() {

      window.onpopstate = function () {
        if (window.location.href.indexOf('#/contractChange') == -1) {
          window.onpopstate = null;
          sessionStorage.clear();
        }
      }

      window.sessionStorage.setItem('pageIndex', 0)
      let cache = JSON.parse(window.sessionStorage.getItem('CHANGE_CONTRACT_INDEX'))
      if (!cache) {
        if (this.alterId) {
          this.getAlertDetail()
        } else {
          this.getDetail()
        }
      } else {
        this.mCode = cache.m_code
        this.tabActive = cache.alter_type.split(',')
        this.instr = cache.alert_description
        this.updateTime = cache.effective_date
        if (cache.agreement_flag == 'Y') {
          let name = cache.agreement_attachment_names.split(',')
          let url = cache.agreement_attachment_urls.split(',')
          name.map((item, index) => {
            this.fileList.push({
              name: item,
              url: url[index]
            })
          })
        }
        this.contractDetail = JSON.parse(window.sessionStorage.getItem('CONTRACT_DETAIL'))
        if (JSON.parse(window.sessionStorage.getItem('CHANGE_CONTRACT_002'))) {
          this.contractDetail.end_date = JSON.parse(window.sessionStorage.getItem('CHANGE_CONTRACT_002')).endDate
        }
      }

      let _this = this
      fileUpload('.upload-file-button', uploadUrl, function (res) {
        _this.progress = ''
        _this.fileList.push(res.json)
      }, function (val) {
        _this.progress = parseInt((val.loaded / val.total) * 100) + '%'
      })
    },
  })
}())
